package com.hmall.trade.config;

import org.springframework.amqp.core.*;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * 延时删除超时未支付订单的消息队列配置
 *
 * @author Zhy
 * @version 1.0
 * @date 2025-03-21 15:07
 */
@Configuration
public class MqConfig {

	/*
	 * 正常队列绑定死信交换机，并设置过期时间 30 分钟
	 *
	 * QueueBuilder.durable：生成持久化队列
	 * deadLetterExchange：设置死信交换机
	 * deadLetterRoutingKey：设置死信路由键
	 * ttl：设置过期时间，单位毫秒
	 */
	@Bean
	public Queue tradePayQueue() {
		return QueueBuilder.durable("trade.pay.queue")
			.deadLetterExchange("trade.delay.dead.exchange")
			.deadLetterRoutingKey("dead.ttl")
			.ttl(30000)
			.build();
	}

	// 设置一个普通交换机，用于接收延时消息
	@Bean
	public DirectExchange tradePayDirect() {
		return new DirectExchange("trade.pay.direct");
	}

	// 将 trade.pay.queue 队列绑定到 trade.pay.direct 交换机，Routing Key 为dead.ttl
	@Bean
	public Binding tradePayQueueBinding(Queue tradePayQueue, DirectExchange tradePayDirect) {
		return BindingBuilder.bind(tradePayQueue).to(tradePayDirect).with("dead.ttl");
	}

}
